import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Button, Form, Row, Col, Radio, Select, Table, DatePicker } from 'antd';
import PropTypes from 'prop-types';
import moment from 'moment';
import styles from "@/common/SearchTable/TableList.less";
import {getDicByCodeSort, getDicByKey} from '@/utils/common';
import MsgModal from "../../modals/msgModal"

const { RangePicker } = DatePicker;
const { Option } = Select;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;

let dateList = [];
const maxLength = 500;

// 海马serviceId 的类型
const serviceIdList = ["1553","1554","1555","1556","1557","1558","1559","1560","1561","1562","1563",
  "1564","1565","1566","1550","1551","1552","1567","1568","1569","1570","1","1571"];

/**
 * 单独抽离日志查询 tab
 * 海马只有其他日志查询，没有DM日志，预留适配DM日志的方法（若适配海马由于字段名称不同，无法直接复用。如需适配，可以不改变原有逻辑进行扩展）
 *
 */

@connect()
// @Form.create()
export default class TboxLogTable extends PureComponent {
  static contextTypes = {
    dicData: PropTypes.array,
  };
  state = {
    formValues:{}, // 查询条件
    refreshDisable: true,  // 刷新
    leftDisable: true,  // 左移
    rightDisable: true,  // 右移
    tboxList: [],   // 数据
    tboxPage: {},   // 分页
    tboxLoading: false, //loading
    type:"other",  // 默认查看的是其他日志
    msgVisible: false, // 详情查看
    msgData:{},
  };
  componentDidMount() {
    this.commonSearch({},"reFresh");
  }

  /**
   *  抽离日志查询的分页方法
   *  type : right left reFresh(查询，刷新,重置)
   *
   */
  commonSearch = (params,type) =>{
    const { dispatch, vin, pdsn, tbox } = this.props;
    this.setState({ tboxLoading: true });  // 查询时设置loading
    dispatch({
      type: 'extendForm/fetch',
      payload: {
        url:"/hmCommon/searchTboxGmdss",
        vin,
        pdsn,
        tbox,
        ...params
      },
      callback: (response) => {
        if (response.code === '0' && response.data) {
          const param = response.data;
          const obj = param.hits.hits;
          const list = obj.map(item => item._source);
          const pageObj = {
            showSizeChanger: true,
            showQuickJumper: true,
            current: 1,
            pageSize: 10,
            showTotal: () =>
              <span>共&nbsp;{list === undefined ? 0 : param.hits.hits.length}&nbsp;条</span>,
          };
          this.setState({ tboxList: list, tboxPage: pageObj });
          // 根据类型以及数据长度来判断禁用
          if(type === "right"){
            // 已经翻到起始页
            if(dateList.length === 0){
              this.setState({
                leftDisable: false,
                rightDisable: true,
              });
            } else {
              this.setState({
                leftDisable: false,
                rightDisable: false,
              });
            }
          } else if(type === "left"){
            if (param.hits.hits.length < maxLength) {
              this.setState({
                leftDisable: true,
                rightDisable: false,
              });
            } else {
              this.setState({
                leftDisable: false,
                rightDisable: false,
              });
            }
          } else if(type ==="reFresh"){
            if (param.hits.hits.length < maxLength) {
              this.setState({
                leftDisable: true,
                rightDisable: true,
              });
            } else {
              this.setState({
                leftDisable: false,
                rightDisable: true,
              });
            }
          }
        }
        this.setState({ tboxLoading: false, refreshDisable: false });
      },
    });
  };
  handleTableChange = (page) => {
    const pagination = {
      current: page.current,
      pageSize: page.pageSize,
    };
    this.setState({
      tboxPage: pagination,
    });
  };
  // 查询其他日志
  handleSearch = (e) => {
    e.preventDefault();
    const {form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const params = {...fieldsValue};
      if(params.rangeTime){
        params.rangeTime = `${moment(params.rangeTime[0]).format('YYYY-MM-DD HH:mm:ss')},${moment(params.rangeTime[1]).format('YYYY-MM-DD HH:mm:ss')}`;
      }
      this.setState({formValues: params});
      dateList = [];
      this.commonSearch(params,"reFresh")
    });
  };
  // 刷新列表
  handleRefresh = () => {
    const { formValues } = this.state;
    this.commonSearch(formValues,"reFresh");
  };
  handleReSet = () => {
    const {resetFields } = this.props.form;
    resetFields();
    this.setState({formValues: {}});
    dateList = [];
    this.commonSearch({},"reFresh");
  };
  // 左移
  handleLeft = () => {
    const { formValues, tboxList } = this.state;
    /**
     * 计算数据的时间点（数据的时间排列顺序，倒序）
     * 【数据开始时间（大）。。。。。。数据结束时间（小）】
     * ① 时间查询条件rangeTime存在  那么时间范围为rangeTime[0]   -    数据结束时间
     * ② 时间查询条件rangeTime不存在  那么时间的范围为   当前时间倒推14天  -   数据结束时间
     *
     */
    if (tboxList.length !== 0) {
      const endDate = tboxList[tboxList.length - 1].colletionDataTime; // 获取数据列表的最后时间
      const searchDate = (moment(endDate).add(1, 's').format('YYYY-MM-DD HH:mm:ss')); // 时间+1s,可以覆盖全部查询的数据
      // 左移开始的时候存取当前数据的最新时间，用于右移直接获取时间
      const startDate = tboxList[0].colletionDataTime; // 获取数据列表的开始时间
      const saveDate = (moment(startDate).add(1, 's').format('YYYY-MM-DD HH:mm:ss'));
      dateList.push(saveDate);
      // 如果查询时间存在且存在左移按钮，那么数据的最后时间作为查询数据的开始时间
      // 如果查询时间不存在且存在左移按钮，那么数据的最后时间作为查询开始时间，查询开始时间以当前往前推14天
      const params = {...formValues};
      if(params.rangeTime){
        const startTime = params.rangeTime.split(",")[0];
        params.rangeTime = `${moment(startTime).format('YYYY-MM-DD HH:mm:ss')},${moment(searchDate).format('YYYY-MM-DD HH:mm:ss')}`;
      } else {
        params.rangeTime = `${moment().subtract(14, 'day').format('YYYY-MM-DD HH:mm:ss')},${moment(searchDate).format('YYYY-MM-DD HH:mm:ss')}`;
      }
     this.commonSearch(params,"left")
    }
  };
  handleRight = () => {
    const { formValues } = this.state;
    const params = {...formValues};
    // 右移的时候直接取出左移存的数据，这个时间作为终止时间，起始时间设为最大（当前时间倒推14天）
    params.rangeTime = `${moment().subtract(14, 'day').format('YYYY-MM-DD HH:mm:ss')},${dateList[dateList.length -1]}`;
    dateList.pop();
    this.commonSearch(params,"right")
  };
  // 当点击tbox日志的时候禁用全部
  onTboxTypeChange = (e) => {
    //  如需适配dm查询，此处是起点
    if (e.target.value === 'dm') {
      this.setState({
        type: e.target.value,
        refreshDisable: true,
        leftDisable: true,
        rightDisable: true,
        tboxList: [],
        tboxPage: {},
      });
    } else if (e.target.value === 'other'){
      this.setState({ type: e.target.value});
      this.handleRefresh();
    }
  };
  handleMsgDetail = (value) => {
    const { vin } = this.props;
    const obj = {...value};
    obj.vin = vin;
    this.setState({ msgVisible: true, msgData: obj });
  };
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const serviceTypeOptions = getDicByCodeSort(this.context.dicData, 'vehicleServiceType');
    const msgTypeOptions = getDicByCodeSort(this.context.dicData, 'vehicleMsgType');
    const { formValues, refreshDisable, leftDisable, rightDisable, tboxList, tboxPage, tboxLoading, type, msgVisible, msgData} = this.state;
    const style = { display: type === 'other' ? '' : 'none'};
    const column = [
      {
        title: 'event_id',
        dataIndex: 'eventId',
        render: (text) => {
          return text;
        },
      }, {
        title: 'service_type',
        dataIndex: 'serviceType',
        render: (text) => {
          return text;
        },
      }, {
        title: 'message_type',
        dataIndex: 'messageType',
        render: (text) => {
          return text;
        },
      }, {
        title: '方向',
        dataIndex: 'direction',
        render: (text) => {
          if (text === '1') {
            return 'TU->TSP';
          } else if (text === '2') {
            return 'TSP->TU';
          } else {
            return text;
          }
        },
      }, {
        title: 'create_time',
        dataIndex: 'colletionDataTime',
        render: (text) => {
          return text;
        },
      }, {
        title: 'message_content',
        dataIndex: 'content',
        render: (text) => {
          if (text) {
            return `${text.substring(0, 20)} ...`;
          } else {
            return text;
          }
        },
      }, {
        title: '说明',
        dataIndex: 'descr',
        render: (text) => {
          return text;
        },
      }, {
        title: 'message_status',
        dataIndex: 'messageStatus',
        render: (text) => {
          return text ? getDicByKey(this.context.dicData, 'vehicleMessageStatus', text) : '';
        },
      }, {
        title: '操作',
        width: 300,
        fixed: 'right',
        dataIndex: 'action',
        render: (text, record) => {
          return (<div><a onClick={() => this.handleMsgDetail(record)}>消息详情</a></div>)
        }
    }];
    return (
      <div>
        <div className={styles.tableListForm}>
          <Form layout="inline">
            <Row gutter={{ md: 16, lg: 24, xl: 48 }}>
              <Col span={6}>
                <FormItem
                  label=""
                >
                  {getFieldDecorator('tboxType', {
                    rules: [{ required: false, message: '请选择' }],
                    initialValue:type
                  })(
                    <RadioGroup onChange={this.onTboxTypeChange}>
                      <RadioButton value="other">其他日志</RadioButton>
                      <RadioButton value="dm">DM日志</RadioButton>
                    </RadioGroup>
                  )}
                </FormItem>
              </Col>
              <Col span={8} style={style}>
                <FormItem
                  label="Service Type"
                >
                  {getFieldDecorator('serviceType', {
                    rules: [{ required: false, message: '请选择' }],
                  })(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input, option) => option.key.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    >
                      {serviceTypeOptions}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={8} style={style}>
                <FormItem
                  label="Message Type"
                >
                  {getFieldDecorator('messageType', {
                    rules: [
                      { required: false, message: '请选择' },
                    ],
                  })(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input, option) => option.key.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    >
                      {msgTypeOptions}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24} style={style}>
              <Col span={8} offset={4}>
                <FormItem label={<span style={{ marginLeft: '3em' }}>时间</span>}>
                  {getFieldDecorator('rangeTime')(
                    <RangePicker
                      allowClear
                      showTime
                      style={{ width: '100%' }}
                      placeholder={['开始时间', '结束时间']}
                      format="YYYY-MM-DD HH:mm:ss"
                    />,
                  )}
                </FormItem>
              </Col>
              <Col span={6}>
                <FormItem
                  label="Service Id"
                >
                  {getFieldDecorator('serviceId', {
                    rules: [
                      { required: false, message: '请选择' },
                    ],
                  })(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                    >
                      { serviceIdList.map(item => {
                        return <Option key={item}>{item}</Option>
                      })}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={6}>
                <div style={{ float:"right"}}>
                  <Button  style={{ marginRight: 12}} disabled={refreshDisable} type="primary" onClick={this.handleSearch}>查询</Button>
                  <Button  disabled={refreshDisable} type="ghost" onClick={this.handleReSet}>重置</Button>
                </div>
              </Col>
            </Row>
          </Form>
        </div>
        <div>
          <Button disabled={leftDisable} type="primary" size="small" icon="double-left" onClick={this.handleLeft} />
          &nbsp;&nbsp;
          <Button disabled={rightDisable} type="primary" size="small" icon="double-right" onClick={this.handleRight} />
          &nbsp;&nbsp;
          <Button disabled={refreshDisable} type="primary" size="small" icon="sync" onClick={this.handleRefresh} />
        </div>
        <div>
          <Table
            size="small"
            pagination={tboxPage}
            dataSource={tboxList}
            columns={column}
            loading={tboxLoading}
            scroll={{ x: '150%' }}
            onChange={this.handleTableChange}
          />
        </div>
        <MsgModal
          msgVisible={msgVisible}
          msg={msgData}
          handleCloseMsg={() => this.setState({ msgVisible: false, msgData:{} })}
        />
      </div>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }
  render() {
    return (
      <div className={styles.tableListForm}>
        {this.renderForm()}
      </div>
    );
  }
}
